
import Layout from './Layout'
import { Button, Form, Input, Spin, Result} from 'antd';
import { useDispatch } from 'react-redux';
import { signup, signup_reset } from '../../store/actions/signup'
import { useSelector } from 'react-redux'
import { useEffect } from 'react';
import Link from 'antd/lib/typography/Link';

 
function Signup() {
  const dispatch = useDispatch()
  // 获取状态
  const { loading, loaded, success, message } = useSelector(state => state.signup)
  // 提交表单
  const handleOnFinish = value => {
    dispatch(signup(value))
    console.log(signup(value))
  }
  // 获取表单实例对象
  const [form] = Form.useForm()
  // 正在发送注册请求显示loading
  const showLoading = () =>{
    if(loading){
      return <Spin />
    }
  }

  // 注册成功清空表单
  useEffect(() => {
    if (loaded && success) form.resetFields()
    // eslint-disable-next-line
  }, [loaded, success])
  
  // 注册成功，显示成功提示
  const show_success = () => {
    if (loaded && success) {
      return (
        <Result
          status="success"
          title="注册成功!"
          extra={[<Button type="primary"><Link to='/login'>登录</Link></Button>]}
        />
      )
    }
  }
  // 注册失败，显示失败提示
  const show_fail = () => {
    if (loaded && !success) {
      return (
        <Result
          status="warning"
          title='注册失败'
          subTitle={message}
        />
      )
    }
  }
  // 注册表单
  const signupForm = () => (
    <Form onFinish={handleOnFinish} form={form}>
      <Form.Item name="name" label='昵称'>
            <Input />
      </Form.Item>
      <Form.Item name="password" label='密码'>
            <Input.Password />
      </Form.Item>
      <Form.Item name="email" label='邮箱'>
            <Input />
      </Form.Item>
      <Form.Item>
          <Button type="primary" htmlType="submit">注册</Button>
      </Form.Item>
    </Form>
  )

  // 离开页面，重置注册状态
  useEffect(() => {
    return () => {
      dispatch(signup_reset())
    }
    // eslint-disable-next-line
  },[])
  return (
    <div>
      <Layout title='注册' subTitle=''>
        {showLoading()}
        {show_success()}
        {show_fail()}
        {signupForm()}
      </Layout>    
    </div>
  )
}

export default Signup
